from pymysql import Connection, err
from settings import DB_HOST, DB_PORT, USE_LOCAL_DB


def get_db_connection():
    conn = None
    if USE_LOCAL_DB:
        with open(r'D:\Code\KnowCode\UserAndPsw.txt', 'r') as fp:
            user = fp.readline().strip()
            psw = fp.readline().strip()
            conn = Connection(
                host=DB_HOST,
                port=DB_PORT,
                user=user,
                password=psw,
                autocommit=True
            )
    else:
        while True:
            user = input('User:')
            psw = input('Password:')
            try:
                conn = Connection(
                    host=DB_HOST,
                    port=DB_PORT,
                    user=user,
                    password=psw,
                    autocommit=True
                )
            except err.OperationalError as oe:
                print('Wrong username or password, please try again!')
                continue
            break
    return conn


if __name__ == '__main__':
    con = get_db_connection()
    print(con.get_server_info())
